<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .img_wrap {
      width: 500px;
      height: 100px;
      display: flex;
      justify-content: space-around;
      margin: 0 auto;
      margin-bottom: 20px;
    }

    .img_wrap img {
      width: 100px;
      height: 100px;
    }

    .img_wrap .active {
      border: 2px solid red;
    }

    #content {
      width: 800px;
      margin: 0 auto;
    }

    .msg_one {
      width: 800px;
      height: 200px;
      border-bottom: 2px solid red;
    }

    .msg_one img {
      width: 80px;
      height: 80px;
    }

    .send_wrap {
      width: 800px;
      margin: 20px auto;
    }
  </style>
</head>

<body>
  <div class="img_wrap">
    <img class="active" src="./images/1.png" alt="">
    <img src="./images/2.png" alt="">
    <img src="./images/3.png" alt="">
    <img src="./images/4.png" alt="">
  </div>
  <div id="content">
    <!-- <div class="msg_one">
      <div>
        <img src="./images/2.png" alt=""> <span>昵称 </span> <span>内容</span>
      </div>
      <div><span>2021-10-20</span> <button>删除</button></div>
    </div>  -->
  </div>
  <div class="send_wrap">
    昵称：<input type="text" id="nick">
    <br>
    <textarea id="txt"></textarea>
    <button id="send">发送</button>
  </div>
  <script src="./jquery-3.4.1.min.js"></script>
  <script>
    if (!localStorage.liulist) {
      localStorage.liulist = JSON.stringify([])  //"[]"
    }
    // 头像切换
    $(".img_wrap img").click(function () {
      $(this).addClass("active").siblings().removeClass("active")
    })
    $("#send").click(function () {
      var obj = {
        imgsrc: $(".active").attr("src"),
        nickname: $("#nick").val(),
        msg: $("#txt").val(),
        date: new Date().toLocaleString(),
      }
      var arr = JSON.parse(localStorage.liulist);
      arr.push(obj)
      localStorage.liulist = JSON.stringify(arr)
      // 清空
      $("#nick").val("")
      $("#txt").val("")
      // 
      show()
    })
    // 渲染
    function show() {
      var arr = JSON.parse(localStorage.liulist);
      var str = ``
      $.each(arr, function (index, ele) {
        str += `    <div class="msg_one">
          <div>
            <img src="${ele.imgsrc}" alt=""> <span>${ele.nickname} </span> <span>${ele.msg}</span>
          </div>
          <div><span>${ele.date}</span> <button onclick="del(${index})">删除</button></div>
        </div> `
      })
      $("#content").html(str)
    }
    show()
    //删除
    function del(index) {
      var arr = JSON.parse(localStorage.liulist);
      arr.splice(index, 1);
      localStorage.liulist = JSON.stringify(arr)
      show();
    }
  </script>
</body>

</html>